package com.shxc.smarttrade.old.activity;

import android.graphics.Matrix;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.shxc.smarttrade.R;
import com.shxc.smarttrade.old.adapter.MyFragmentAdapter;
import com.shxc.smarttrade.old.bean.EventDatas;
import com.shxc.smarttrade.old.bean.TradeCategory;
import com.shxc.smarttrade.old.constants.EventContents;
import com.shxc.smarttrade.old.constants.URLContents;
import com.shxc.smarttrade.old.fragment.EnergyFragment;
import com.shxc.smarttrade.old.fragment.IndexFragment;
import com.shxc.smarttrade.old.fragment.MetalFragment;
import com.shxc.smarttrade.old.fragment.MoneyFragment;
import com.shxc.smarttrade.old.myview.MyProgressDialog;
import com.shxc.smarttrade.old.utils.BaseUtils;
import com.shxc.smarttrade.old.utils.CloseAllActivity;
import com.shxc.smarttrade.old.utils.MyOkHttpUtils;
import com.shxc.smarttrade.old.utils.SpUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * Created by jcdev1 on 2017/5/16.
 */

public class AddTradeCategoryActivity extends FragmentActivity implements View.OnClickListener {

    private Animation animation = null;
    private int offset;
    private int fromX = 0;
    MyProgressDialog dialog;
    public List<TradeCategory.DataBean.SymbolsBean> money;
    public List<TradeCategory.DataBean.SymbolsBean> index;
    public List<TradeCategory.DataBean.SymbolsBean> metal;
    public List<TradeCategory.DataBean.SymbolsBean> energy;

    private List<Fragment> fragmentList;
    @BindView(R.id.rl_left)
    RelativeLayout rlLeft;
    @BindView(R.id.tv_center)
    TextView tvCenter;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.tv_energy)
    TextView tvEnergy;
    @BindView(R.id.tv_index)
    TextView tvIndex;
    @BindView(R.id.tv_oil)
    TextView tvOil;
    @BindView(R.id.iv_tag)
    ImageView ivTag;
    @BindView(R.id.vp_trade)
    ViewPager vpTrade;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    TradeCategory tc = (TradeCategory) msg.obj;
                    String errorcode = tc.getErr_code();
                    String errmessage = tc.getErr_msg();
                    if (errorcode.equals("0")) {
                        List<TradeCategory.DataBean.SymbolsBean> sb = tc.getData().getSymbols();
                        money = new ArrayList<>();
                        index = new ArrayList<>();
                        metal = new ArrayList<>();
                        energy = new ArrayList<>();
                        //将数据分组
                        for (TradeCategory.DataBean.SymbolsBean symbo : sb) {
                            if (symbo.getGroup().equals("0")) {
                                money.add(symbo);
                            } else if (symbo.getGroup().equals("1")) {
                                index.add(symbo);
                            } else if (symbo.getGroup().equals("2")) {
                                metal.add(symbo);
                            } else {
                                energy.add(symbo);
                            }
                        }
                        //通知各个Fragment数据已经准备完毕，请需要的自己注册获取
                        EventBus.getDefault().post(new EventDatas(EventContents.ADD_TRADE_CATEGORY_ACTIVITY_ONE, null));
                    } else {
                        Toast.makeText(getApplicationContext(), errmessage, Toast.LENGTH_SHORT).show();
                    }

                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_trade_category);
        CloseAllActivity.getScreenManager().pushActivity(this);
        ButterKnife.bind(this);
        initView();
        initListener();
        initFragment();
        int userId = SpUtils.getInt(getApplicationContext(), "userId", 0);
        dialog.show();
        initDatas(userId);

    }

    /**
     * 初始化View
     */
    private void initView() {
        tvCenter.setText("添加交易品种");
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) ivTag.getLayoutParams();
        int screenWidth = BaseUtils.getScreenWidth(getApplicationContext());
        params.width = screenWidth / 8;//布局文件中必须以dp为单位，否者无法设置其宽高
        params.leftMargin = screenWidth / 16;
        ivTag.setLayoutParams(params);
        Matrix matrix = new Matrix();
        matrix.postTranslate(0, 0);
        ivTag.setImageMatrix(matrix);
        offset = screenWidth / 4;
        dialog = new MyProgressDialog(this);
        dialog.setCancelable(false);

    }

    /**
     * 初始化监听器
     */
    private void initListener() {
        rlLeft.setOnClickListener(this);
        tvMoney.setOnClickListener(this);
        tvEnergy.setOnClickListener(this);
        tvIndex.setOnClickListener(this);
        tvOil.setOnClickListener(this);
    }

    /**
     * 向viewpager中填充fragment
     */
    private void initFragment() {
        fragmentList = new ArrayList<>();
        fragmentList.add(new MoneyFragment());
        fragmentList.add(new IndexFragment());
        fragmentList.add(new MetalFragment());
        fragmentList.add(new EnergyFragment());
        vpTrade.setOffscreenPageLimit(4);
        vpTrade.setAdapter(new MyFragmentAdapter(getSupportFragmentManager(), fragmentList));
        vpTrade.setOnPageChangeListener(new MyPagerListener());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_left:
                finish();
                break;
            case R.id.tv_money:
                vpTrade.setCurrentItem(0, true);
                break;
            case R.id.tv_energy:
                vpTrade.setCurrentItem(1, true);
                break;
            case R.id.tv_index:
                vpTrade.setCurrentItem(2, true);
                break;
            case R.id.tv_oil:
                vpTrade.setCurrentItem(3, true);
                break;
        }
    }

    class MyPagerListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            tvMoney.setTextColor(getResources().getColor(R.color.main_text_color));
            tvEnergy.setTextColor(getResources().getColor(R.color.main_text_color));
            tvIndex.setTextColor(getResources().getColor(R.color.main_text_color));
            tvOil.setTextColor(getResources().getColor(R.color.main_text_color));
            switch (position) {
                case 0:
                    tvMoney.setTextColor(getResources().getColor(R.color.main_color));
                    animation = new TranslateAnimation(fromX, 0, 0, 0);
                    fromX = 0;
                    break;
                case 1:
                    tvEnergy.setTextColor(getResources().getColor(R.color.main_color));
                    animation = new TranslateAnimation(fromX, offset, 0, 0);
                    fromX = offset;
                    break;
                case 2:
                    tvIndex.setTextColor(getResources().getColor(R.color.main_color));
                    animation = new TranslateAnimation(fromX, offset * 2, 0, 0);
                    fromX = 2 * offset;
                    break;
                case 3:
                    tvOil.setTextColor(getResources().getColor(R.color.main_color));
                    animation = new TranslateAnimation(fromX, offset * 3, 0, 0);
                    fromX = 3 * offset;
                    break;
            }
            animation.setFillAfter(true);
            animation.setDuration(200);
            ivTag.startAnimation(animation);
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    }

    /**
     * 初始化数据
     */
    private void initDatas(int userId) {
        Map<String, Object> map = new HashMap<>();
        map.put("accessToken", SpUtils.getString(this, "accessToken", ""));
        map.put("userId", userId + "");
        MyOkHttpUtils.getServiceDatas(this,map, URLContents.ADD_TRADE_CATEGORY_ACTIVITY_SYMBOL, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void success(String response, int id) {

                Gson gson = new Gson();
                TradeCategory tradeCategory = gson.fromJson(response, TradeCategory.class);
                Message msg = Message.obtain();
                msg.what = 0;
                msg.obj = tradeCategory;
                handler.sendMessage(msg);
                dialog.dismiss();

            }

            @Override
            public void faild(Call call, Exception e, int id) {
                dialog.dismiss();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CloseAllActivity.getScreenManager().popActivity(this);
    }

}
